/**
 * @Description:
 * @author 紫霞
 * @since 2019/1/17
 */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
import FlagBtn from 'widget/FlagBtn/FlagView'
// 引入antd的组件
import { Row, Col, Card, Button, Tabs, Form, Popconfirm, Modal, } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
//引用listPage
import ListPage from 'widget/PageTmpl/ListPage'
import cx from 'classnames'
// 当前组件样式
import styles from './activityListStyle.less'
import { Grid, QueryCondition } from 'widget/Grid/index'
import { AdvanceSearch } from 'widget/CollapsiblePanels/index'
import Keypress  from 'widget/Keypress'
import { chunk } from 'lodash'

/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const TabPane = Tabs.TabPane
function includes (item,arr) {
  let flag=false
  if(arr.indexOf(item+'')>-1){
    flag=true
  }
  return flag
}

const routeView = function ({dispatch, model, form}) {
  // 表单的子函数
  const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
  // 取出model对象，命名空间
  const {modelObj, namespace} = model
  let {loading, btnLoading, modalObj, currentItem, queryList, tableData, pageConfig,query} = modelObj
  // modelObj.xxx获取model中状态机的值
  console.log('modelObj', modelObj)
  // 点击处理事件
  const clickHandler = (e) => {
    // 分发到model文件中effects的xxx方法
    dispatch({
      type: `${namespace}/xxx`,
      payload: {}
    })
  }


  // 序号  活动名称 活动时间段  状态 创建人  创建时间
  const columns = [
    {
      title: '序号', dataIndex: 'key', key: 'key', width: 60,
      render: function (value, item, index) {
        return index + 1
      }
    },
    {
      title: '活动名称', dataIndex: 'name', key: 'name',width:160,
      render: function (value, item, index) {
        return <span>{item.seckillActivity.name}</span>
      }
    },
    {
      title: '活动时间段', dataIndex: 'seckillTimeIntervals', key: 'seckillTimeIntervals',width: 350,
      render: function (value, item, index) {
        let arr = []
        value.map((item, index) => {
          let time =`${item.startTime||''}${item.endTime&&' ~ '||''}${item.endTime||''}`
          arr.push(time)
        })
        let html = arr.join('<br />')||''
        return <div style={{ maxHeight: '60px', overflowY: 'auto' }} dangerouslySetInnerHTML={{ __html: html }}>
        </div>
      }

    },
    {//1，未发布。2，已发布，3已撤销
      title: '状态', dataIndex: 'published', key: 'published', width: 80,
      render: function (value, item, index) {
        return <span> {{1:'未发布',2:'已发布',3:'已撤销',}[item.seckillActivity.published]}</span>
      }
    },
    {
      title: '创建人', dataIndex: 'createPerson', key: 'createPerson',width: 80,
      render: function (value, item, index) {
        return <span>{item.seckillActivity.createPerson}</span>
      }
    },
    {
      title: '创建时间', dataIndex: 'createTime', key: 'createTime',width: 180,
      render: function (value, item, index) {
        return <span>{item.seckillActivity.createTime}</span>
      }
    },
    // {
    //   title: '备注', dataIndex: 'remark', key: 'remark',
    //   render: function (value, item, index) {
    //     return <span>{item.seckillActivity.remark}</span>
    //   }
    // },
  ]
  // 表格模板配置
  const gridProps = {
    nameSpace: namespace,
    data: {
      columns: [].concat(columns, generateAction()),
      pageConfig, tableData
    },
    pageChange: (pageNo, pageSize) => {
      console.log(pageNo, pageSize)
      dispatch({ type: `${namespace}/pageChange`, payload: {pageNo, pageSize } });
    },
    scroll: {x: 1000},
    loading
  }

  // 表格操作区域
  function generateAction () {
    return {
      title: '操作',
      key: 'operation',
      width: 180,
      render: (data, record, index) => {
        return (
          <span>
             <FlagBtn
                 node={<a onClick={() => routerGo({type: 'detail', item: record.seckillActivity})}>查看详情<span className="ant-divider" /></a>}
                 btnId={'90102'}
             >
            </FlagBtn>
            {includes(record.seckillActivity.published,['1','2'])&&

            <FlagBtn
                node={  <a  onClick={() => routerGo({ type: 'edit', item: record.seckillActivity })}>修改<span className="ant-divider" /></a>}
                btnId={'90103'}
                >
                </FlagBtn>
            }
            {
              record.seckillActivity.published==1?
              <FlagBtn
                  btnId={'90104'}
                  node={ <a  onClick={() => {
                    dispatch({
                      type:`${namespace}/deleted`,
                      payload:{
                        seckillActivityId:record.seckillActivity.seckillActivityId
                      }
                    })
                  }}>删除<span className="ant-divider" /></a>}
                
                  >
              </FlagBtn>:null
            }
            {
              <FlagBtn
                  btnId={'90105'}
                  node={ <a  onClick={() => {
                    hashHistory.push({
                      pathname: "home/seckillAuctions/enrollList",
                      query: {seckillActivityId:record.seckillActivity.seckillActivityId||''}
                    })
                  }}>查看报名情况</a>}
                
                  >
              </FlagBtn>
            }
          </span>
        )
      }
    }
  }

  // 详情页跳转
  function routerGo ({type, item = {}}) {
    let urlArray = MODULE_TO_ROUTES[namespace].urlArray
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {isReloadFirstPage: type === 'add'}
    })
    hashHistory.push({
      pathname: urlArray[0],
      query: {pageType: type, id: item.seckillActivityId || ''}
    })
  }


  //修改状态
  const changeState = (payload) => {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {...payload}
    })
  }
  //修改状态
  const inputChange = (payload) => {
    let {key, value} = payload
    dispatch({
      type: `${namespace}/inputChange`,
      payload: {
        ...payload
      }
    })
  }
  //查询
  const onSearch = (payload) => {
    dispatch({
      type: `${namespace}/search`,
      payload: payload
    })
  }
  const queryReset = (payload) => {
    dispatch({
      type: `${namespace}/queryReset`,
      payload: payload
    })
  }

  return (
    <div className={cx('pageLayout')}>
      {/*监控键盘事件，自动刷新数据*/}
      <Keypress keyCode={13} cbk={()=>{
        onSearch();
      }} />
      <div className="public_listMain">
        <div className="functionButton">
          <span className={styles.red}>(重要提示,前端需要配置广告才可以链接到秒杀活动的页面)</span>
          {/*<Button type="primary" onClick={() => routerGo({type: 'add',})}>新增</Button>*/}
            <FlagBtn
                node={  <Button type="primary" onClick={() => routerGo({type: 'add',})}>创建秒杀活动</Button>}
                btnId={'90101'}
            >
            </FlagBtn>
        </div>
        <AdvanceSearch
          footer={
            <span>
                <Button className={styles.btn} type="primary" htmlType="submit" onClick={() => onSearch()} loading={modelObj.loading}>搜索</Button>
                <Button className={styles.btn} onClick={() => dispatch({ type: `${namespace}/queryReset` })}>重置</Button>
              </span>
          }
        >
          <QueryCondition
            data={queryList}
            inputChange={(key, value) => dispatch({type: `${namespace}/inputChange`, payload: {key, value}})}
          />
        </AdvanceSearch>
        {/* 表格区域 */}
        <div className="boxShadow">
          {/* 搜索条件 */}

          {/* 添加用户 */}
          <Grid {...gridProps} />
        </div>
      </div>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))
